#include "tcp_client_test.h"
#include <arpa/inet.h>
namespace sdx {
TcpClient::TcpClient() { std::cout << "TcpClient construct" << std::endl; }
TcpClient::~TcpClient() { std::cout << "TcpClient distruct" << std::endl; }

void TcpClient::createSocket() {
  socketFd = socket(AF_INET, SOCK_STREAM, 0);
  if (socketFd == -1) {
    std::cout << "create socket failed" << std::endl;
    exit(EXIT_FAILURE);
  }
}
void TcpClient::setserverAddr() {
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  serverAddr.sin_port = htons(SEVERPORT);
  serverAddr.sin_family = AF_INET;
  bzero(&serverAddr.sin_zero, 8);
}
void TcpClient::connect2server() {
  ret = connect(socketFd, (struct sockaddr *)&serverAddr,
                sizeof(struct sockaddr));
  if (ret == -1) {
    std::cout << "connect to server failed" << std::endl;
    exit(EXIT_FAILURE);
  }
  std::cout << "success to connet server" << std::endl;
}
int TcpClient::sendMessage() {
  memset(&sendBuff, 0, sizeof(sendBuff));
  std::cout << "<<< send: " << std::endl;
  std::cin >> sendBuff;
  if (strcmp(sendBuff, "quit") == 0) {
    return 1;
  }
  ret = send(socketFd, sendBuff, strlen(sendBuff), 0);
  if (ret == -1) {
    std::cout << "connection failed" << std::endl;
    exit(EXIT_FAILURE);
  }
  return 0;
}
void TcpClient::recvMessage() {
  std::cout << ">>> recv: " << std::endl;
  recvBuff[0] = '\0';
  int datalen = recv(socketFd, recvBuff, MESSAGE_SIZE, 0);
  recvBuff[datalen] = '\0';
  std::cout << recvBuff << std::endl;
}
void TcpClient::closeSocket() { close(socketFd); }
} // namespace sdx
